// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let id = event.id
  if(event.judge == 1){
    let res = db.collection('views').where({
      id,myid:wxContext.OPENID
    }).get();
    return res
  }
  let dataPage = await db.collection('views').where({
    id,myid:wxContext.OPENID
  }).get()
  if(dataPage.data.length == 0){
    await db.collection('views').add({
      data:{
        id,myid:wxContext.OPENID
      }
    })
    await db.collection('list_1').doc(id).update({
      data:{
        follows:_.inc(1)
      }
    })
    let res = await db.collection('list_1').doc(id).get();
    return{
      res,
      code:1
    }
  }else{
    await db.collection('views').where({
      id,myid:wxContext.OPENID
    }).remove()
    await db.collection('list_1').doc(id).update({
      data:{
        follows:_.inc(-1)
      }
    })
    let res = await db.collection('list_1').doc(id).get();
    return{
      res,
      code:0
    }
  }
}